package com.sqx.modules.timedtask.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sqx.common.utils.DateUtils;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.chat.controller.app.AppChatSocket;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.errand.entity.Indent;
import com.sqx.modules.errand.service.IndentService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.pay.controller.app.AliPayController;
import com.sqx.modules.pay.dao.PayDetailsDao;
import com.sqx.modules.pay.service.WxService;
import com.sqx.modules.tbCoupon.entity.TbCouponUser;
import com.sqx.modules.tbCoupon.service.TbCouponUserService;
import com.sqx.modules.timedtask.service.RiderLocationService;
import com.sqx.modules.utils.SenInfoCheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class AutoSendOrder {

    @Autowired
    private UserService userService;
    @Autowired
    private IndentService indentService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private TbCouponUserService couponUserService;
    @Autowired
    private MessageService messageService;


    @Scheduled(fixedRate  = 2000, zone = "Asia/Shanghai")
    /**
     * 新人奖励制度到期监听
     */
    public void userRewardTime() {
        List<UserEntity> userEntityList = userService.list(new QueryWrapper<UserEntity>().eq("is_enable_reward", 1));
        for (UserEntity userEntity : userEntityList) {
            if (LocalDateTime.now().isAfter(userEntity.getCloseRewardTime())) {
                userEntity.setIsEnableReward(0);
                userService.updateById(userEntity);
            }
        }
    }

    /**
     * 订单定时取消
     */
    @Scheduled(fixedRate  = 2000, zone = "Asia/Shanghai")
    public void cancelIndent() {
        List<Indent> indentList = indentService.list(new QueryWrapper<Indent>().eq("indent_state", 0));
        int minute = Integer.parseInt(commonInfoService.findOne(346).getValue());
        for (Indent indent : indentList) {
            Duration duration = Duration.between(indent.getCreateTime(), LocalDateTime.now());
            if (duration.toMinutes() > minute) {
                //将优惠券修改为未使用状态
                if (indent.getCouponId() != null) {
                    TbCouponUser couponUser = couponUserService.getById(indent.getCouponId());
                    couponUser.setStatus(0);
                    couponUserService.updateById(couponUser);
                }
                indent.setIndentState(5);
                indentService.updateById(indent);
            }
        }
    }

    //新订单推送
    @Scheduled(fixedRate  = 2000, zone = "Asia/Shanghai")
    public void pushOrderMsg() throws IOException {
        String isOpenMsg = String.valueOf(commonInfoService.findOne(340).getValue());
        Double range = Double.parseDouble(commonInfoService.findOne(339).getValue());
        CommonInfo one = commonInfoService.findOne(338);
        if ("是".equals(isOpenMsg)) {
            List<Indent> indentList = indentService.list(new QueryWrapper<Indent>().eq("indent_state", 0).eq("is_push_msg", 0));
            for (Indent indent : indentList) {
                //获取要通知的师傅列表
                List<UserEntity> userEntityList = userService.getNearByRider(range, indent.getShipAddressLongitude(), indent.getShipAddressLatitude());
                for (UserEntity userEntity : userEntityList) {
                    if (userEntity.getRiderOpenId() != null) {
                        List<String> msgList = new ArrayList<>();
                        String address = indent.getShipAddress() + "" + indent.getDeliveryAddress();
                        if (address.length() >= 20) {
                            address = address.substring(0, 15) + "...";
                        }
                        //地址
                        msgList.add(0, address);
                        //订单金额
                        msgList.add(1, indent.getEstimateMoney().multiply(new BigDecimal(userEntity.getRate())).setScale(2,BigDecimal.ROUND_FLOOR).toString());
                        //下单时间
                        msgList.add(2, DateUtils.format(new Date()));
                        String phone = indent.getShipUserPhone();
                        if ("2".equals(indent.getIndentType())) {
                            phone = indent.getCustomPhone();
                        }
                        //电话
                        msgList.add(3, phone);
                        msgList.add(4, "生意来了，立即去接单>");
                        SenInfoCheckUtil.sendRiderMsg(userEntity.getRiderOpenId(), one.getValue(), msgList, 2);

                    }
                    //app端师傅消息推送
                    if (StringUtils.isNotEmpty(userEntity.getClientRiderId())) {
                        String content = "生意来了，立即去接单>";
                        userService.pushToSingleQiShou("新订单通知", content, userEntity.getClientRiderId());
                    }
                    MessageInfo messageInfo = new MessageInfo();
                    messageInfo.setTitle("订单提醒");
                    messageInfo.setContent("有一条新订单");
                    messageInfo.setUserId(userEntity.getUserId().toString());
                    messageInfo.setCreateAt(DateUtils.format(new Date()));
                    messageInfo.setIsSee("0");
                    messageInfo.setUserType(2);
                    messageInfo.setType("1");
                    messageService.save(messageInfo);
                }
                Indent pushIndent = new Indent();
                pushIndent.setIndentId(indent.getIndentId());
                pushIndent.setIsPushMsg(1);
                indentService.updateById(pushIndent);
            }
        }
    }
}
